{% load static %}
<link rel="stylesheet" href="{% static 'css/form.css' %}">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> 

<div class="container">
    <!-- <h1>学生信息表单</h1> -->
    {% if student.pk %}
        <h1>编辑教师信息</h1>
    {% else %}
        <h1>新增教师信息</h1>
    {% endif %}

    <form method="post">
        {% csrf_token %}
        {% for field in form %}
        <div class="form-group">
            <label for="{{ field.id_for_label }}">{{ field.label }}:</label>
            {{ field }}
            {% if field.help_text %}
            <small class="form-text text-muted">{{ field.help_text }}</small>
            {% endif %}
            {% if field.errors %}
                <div class="error">{{ field.errors }}</div>
            {% endif %}
        </div>
        {% endfor %}
        <div class="handleButton">
            <button type="submit" id="saveButton">保存</button>
            <button type="button" id="cancelButton" onclick="window.parent.Swal.close()">取消</button>

        </div>
    </form>
</div>

{% if teacher.pk %}
    <script>
        var actionUrl = "{% url 'teacher_update' teacher.pk %}";
    </script>
{% else %}
    <script>
        var actionUrl = "{% url 'teacher_create' %}";
    </script>
{% endif %}

<script>
    document.addEventListener('DOMContentLoaded', function(){
        const form = document.querySelector('form');
        const url = actionUrl;     //"{% url 'student_create' %}";

        form.addEventListener('submit', function(e){
            e.preventDefault(); // 阻止默认提交行为

            let formData = new FormData(form);
            //使用fetch发送请求 
            fetch(url, {
                method:'POST',
                body:formData,
                headers:{
                    'x-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': formData.get('csrfmiddlewaretoken'), // 添加CSRF令牌
                }
            }).then(response => response.json())
            .then(data => {
                if(data.status === 'success'){
                    Swal.fire({
                        icon:'success',
                        title:data.messages,
                        text:'数据已提交',
                    }).then((result) => {       //数据提交成功后的操作 跳转到列表页
                        if(result.value){
                            window.parent.location.reload() //刷新父页面
                        }
                    })
                }else{
                    // 解析JSNON字符串
                    const errors = JSON.parse(data.messages);
                    console.log(errors);
                    //构造错误信息的文本
                    let errorMessage = '';
                    for (const field in errors){
                        if (errors.hasOwnProperty(field)){
                            errors[field].forEach(error => {
                                errorMessage += `<li style="color:red; text-align:left; margin-left:100px; "> ${error.message}`
                            });
                        }
                    }
                    Swal.fire({
                        icon:'error',
                        title:'提交错误',
                        html:errorMessage,
                        confirmButtonText:'关闭',
                    })
                }
                               
            })
            .catch(error => {
                Swal.fire({
                    icon:'error',
                    title:'网络请求失败',
                    text:'无法连接到服务器，请稍后再试啊！！！',
                    confirmButtonText:'关闭'
                })
            })
        })
    })    
</script>